package com.grape.springbootgradle20220520.network;


import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author pan_jin
 * @Description: $ http qingqiu
 * @Date: 2022/5/25 10:17
 * @Version: 1.0.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */
public class HttpRequestDemo {
    static HttpClient httpClient = HttpClient.newBuilder().build();

    public static void main(String[] args) throws InterruptedException, IOException, URISyntaxException {
        httpGet();
    }

    /**
    *@Author: pan_jin
    *@Date: 2022/5/25 10:52
    *@Description: get请求
    *@params: []
    *@Return: void
    */
    static void httpGet() throws URISyntaxException, IOException, InterruptedException {
        String url="https://www.sina.com.cn/";
        HttpRequest httpRequest=HttpRequest.newBuilder(new URI(url))
                .header("User-Agent","Java HttpClient").header("Accept","*/*")
                .timeout(Duration.ofSeconds(5))
                .version(HttpClient.Version.HTTP_2)
                .build();
        HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        Map<String, List<String>> map = response.headers().map();
        for (String s : map.keySet()) {
            System.out.println(s+":"+map.get(s).get(0));
        }
        System.out.println(response.body().substring(0, 1024) + "...");
    }
}
